package com.haoran.dwz.common.util;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.runtime.RuntimeSchema;

public class ProtoStuffUtil<T> {
	
//	private RuntimeSchema<T> schema;
//	
//	@SuppressWarnings("unchecked")
//	public ProtoStuffUtil(T t){
//		schema =  (RuntimeSchema<T>) RuntimeSchema.createFrom(t.getClass());
//	}
	
	public static <T> byte[] serializate(T t) {
		@SuppressWarnings("unchecked")
		RuntimeSchema<T>  schema =  (RuntimeSchema<T>) RuntimeSchema.createFrom(t.getClass());
		byte[] byteArray = ProtostuffIOUtil.toByteArray(t, schema, LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE*100));
		return byteArray;
	} 
	
	
	public static <T> T deserializate(byte[] data,Class clazz) {
		@SuppressWarnings("unchecked")
		RuntimeSchema<T>  schema =  (RuntimeSchema<T>) RuntimeSchema.createFrom(clazz);
		T t = schema.newMessage();
		ProtostuffIOUtil.mergeFrom(data, t, schema);
		return t;
	}
	
}
